<?php
class Cms_Validate_UniqueUsername extends Zend_Validate_Abstract
{
    const USERNAME_EXISTS = 'usernameExists';

    protected $_messageTemplates = array(
        self::USERNAME_EXISTS => 'Username "%value%" already exists in the system',
    );

    public function __construct(Cms_Model_Administrator $model)
    {
        $this->_model = $model;
    }

    public function isValid($value, $context = null)
    {
        $this->_setValue($value);
        $currentAdministrator = isset($context['adminId']) ? $this->_model->getAdministratorById($context['adminId']) : null;
        $administrator = $this->_model->getAdministratorByUsername($value, $currentAdministrator);
        
        if (null === $administrator) {
            return true;
        }

        $this->_error(self::USERNAME_EXISTS);
        return false;
    }
}
